import { deepCopy } from '@u/common.js';

export function changeForm(data, obj = {}, reverse = false, { valueName = 'value', isInheritValue = true } = {}) {
  const form = deepCopy(obj);
  for (const k in data) {
    if (data[k].readonly && !reverse) { // 如果只是只读，不需要赋值
      continue;
    }
    if (!data[k].slot) {
      const names = data[k].belong ? data[k].belong.split('.') : [k];
      if (names.length == 1) {
        if (reverse) {
          data[k][valueName] = form[names[0]] !== undefined && form[names[0]] !== '' && form[names[0]] !== null
            ? form[names[0]] : isInheritValue ? data[k][valueName] : '';
        } else {
          form[names[0]] = data[k][valueName];
        }
      } else {
        let tmp = form;
        names.map((n, i) => {
          if (i != names.length - 1) {
            if (!tmp[n] || !(tmp[n] instanceof Object)) {
              tmp[n] = {};
            }
            tmp = tmp[n];
          } else {
            if (reverse) {
              data[k][valueName] = tmp[n] !== undefined && tmp[n] !== '' && tmp[n] !== null ? tmp[n] : isInheritValue ? data[k][valueName] : '';
            } else {
              tmp[n] = data[k][valueName];
            }
          }
        });
      }
    }
  }
  return form;
}
